import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, Image, FlatList, Dimensions
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { SearchInput } from '../../../component/SearchInput.js';
import ToastUtil from '../../../utils/toast'
import HTTP from '../../../utils/http'
const scale = GLOBAL.SCALE;
const ScreenWidth = Dimensions.get('window').width;

export class ProductSelectPage extends Component {
	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '商品列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	/*
		type:
		意向客户-INTENTION
		长约执行-EXECUTE
	*/
	constructor(props) {
		super(props);
		let { pushIndex, orderId, type } = props.navigation.state.params;
		this.data = {
			params: {
				orderId: orderId
			},
		}
		this.state = {
			newLotData: [],  // 待审批
			status: 'loading',
			loadIcon: false,  // 下拉涮新的 图标
			selectIndex: pushIndex
		}
		this.pageNo = 1;
		this.totalPage = 1;
		this.searchCode = '';
		this.onrefresh = false; //是否显示下拉icon
		this.isIntention = false; // 意向客户列表
		this.isExecute = false; // 长约执行列表
		switch (type) {
			case 'INTENTION':
				this.isIntention = true;
				return
			case 'EXECUTE':
				this.isExecute = true;
				return
		}
	}

	componentWillMount () {
		this._getListData();
	}

	//获取列表
	async _getListData () {
		let sendData = {
			pageNo: this.pageNo,
			orderId: this.data.params.orderId
		}
		let url = '';
		if (this.isIntention) {
			sendData.queryType = 'ORDER_ITEM_LIST';
			url = API.ORDER_DETAIL;
		} else {
			sendData.searchCode = this.searchCode;
			url = API.LONG_PRODUCT_LIST;
		}
		this.setState({
			loadIcon: this.onrefresh,
			status: this.onrefresh ? 'data' : 'loading'
		})
		let responseData = await HTTP.POST(API_GENERATE(url), sendData);
		if (responseData) {
			this.totalPage = responseData.totalPage;
			let productList = this.isIntention ? responseData : responseData.rows
			this.setState({
				newLotData: this.pageNo == 1 ? productList : this.state.newLotData.concat(productList),
				status: productList.length ? 'data' : 'empty',
				loadIcon: false
			})
		} else {
			this.setState({
				status: 'error',
				loadIcon: false
			})
		}
	}

	// 下拉更新函数
	_isLoadRefresh () {
		this.pageNo = 1;
		this.onrefresh = true;
		this._getListData();
	}

	//上拉加载
	_loadData () {
		if (this.totalPage > this.pageNo) {
			this.pageNo++;
			this.onrefresh = true;
			this._getListData();
		}
	}

	//数据加载出错回调
	_onErrorPress = () => {
		this.setState({
			status: 'loading'
		}, () => {
			this.pageNo = 1;
			this.onrefresh = false;
			this._getListData();
		})
	}

	//选中
	_selectFn = (index, itemData) => {
		if (itemData && itemData.isExpired == '2') {
			ToastUtil.showWarning('操作失败，请检查商品交易资质是否过期或缺失！');
			return
		}
		this.setState({
			selectIndex: index
		}, () => {
			if (this.isExecute) itemData.itemId = null;
			setTimeout(() => {
				this.props.navigation.state.params.callBack(itemData, index);
				// this.props.navigation.navigate('ProductFormPage');
				this.props.navigation.goBack();
			})
		})
	}


	// 一条数据
	_renderItem (data) {
		let { goodsName, price, quantity, priceFormulaDesc, udPrice } = data.item;
		let { selectIndex } = this.state;
		let index = data.index;
		return (
			<TouchableOpacity onPress={() => { this._selectFn(index, data.item) }}>
				<View style={styles.exBox}>
					{selectIndex == index ? (
						<Image source={require('../../../imgs/apply/selectLong.png')} style={styles.imgPosition} />
					) : null}
					<View style={styles.exHead}>
						<View style={styles.exHeadLeft}>
							<Text style={styles.exHeadTitle}>{goodsName}</Text>
						</View>
					</View>
					<View style={styles.exContent}>
						<View style={[styles.exComItem]}>
							<Text style={styles.exName}>数量：</Text>
							<Text style={styles.exValue} numberOfLines={1}>{quantity}</Text>
						</View>
						<View style={[styles.exComItem]}>
							<Text style={styles.exName}>价格：</Text>
							<Text style={styles.exValue} numberOfLines={1}>{price}</Text>
						</View>
						<View style={[styles.exComItem]}>
							<Text style={styles.exName}>结算价：</Text>
							<Text style={styles.exValue} numberOfLines={1}>{priceFormulaDesc}</Text>
						</View>
						<View style={[styles.exComItem]}>
							<Text style={styles.exName}>升贴水：</Text>
							<Text style={styles.exValue} numberOfLines={1}>{udPrice}</Text>
						</View>
					</View>
				</View>
			</TouchableOpacity>
		)
	}

	searchProduct = (txt) => {
		this.searchCode = txt;
		this.pageNo = 1;
		this.onrefresh = false;
		this._getListData();
	}


	render () {
		let { status } = this.state;
		let searchIcon = require('../../../imgs/customer/searchLeft.png');

		return (
			<View style={[styles.container]}>
				{
					this.isExecute ?
						(<View style={styles.searchWrap}>
							<View style={styles.searchInput}>
								<SearchInput
									placeholder={'商品名称'}
									inputLeftIcon={searchIcon}
									setKeyWord={(txt) => { this.searchProduct(txt) }}
									onChangeText={(txt) => { }}
									onSubmitEditing={(txt) => { }}
									inputViewStyle={styles.searchStyle}
								/>
								<View style={{ paddingLeft: 12 * scale, paddingRight: 12 * scale, paddingTop: 10 * scale, paddingBottom: 10 * scale }}>
									<Text style={{ fontSize: 12 * scale, opacity: .8 }}>*商品已根据框架及企业绑定关系进行过滤，若本次交易商品不存在，请维护框架对应的结算公式或检查操作人与企业商品绑定关系。</Text>
								</View>
							</View>
						</View>) : null
				}
				{
					status == 'data' ? (
						<View style={styles.listBox}>
							<FlatList
								data={this.state.newLotData}
								renderItem={(data) => this._renderItem(data)}
								refreshing={this.state.loadIcon}
								onRefresh={this._isLoadRefresh.bind(this)}
								onEndReachedThreshold={1}
								onEndReached={() => { this._loadData(); }}
							/>
						</View>
					) : null
				}
				<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this._onErrorPress} />
			</View >
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.light,
	},
	searchWrap: {
		backgroundColor: '#fff',
		// height: 60 * scale,
		width: ScreenWidth
	},
	searchInput: {
		width: ScreenWidth - 20 * scale,
		height: 84 * scale,
		position: 'relative',
		backgroundColor: '#fff',
		marginTop: 10 * scale,
		marginLeft: 10 * scale
	},
	exBox: {
		marginTop: 10 * scale,
		height: 140 * scale,
		backgroundColor: '#fff',
	},
	exHead: {
		height: 44 * scale,
		marginLeft: 12 * scale,
		marginRight: 12 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.gray,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	exHeadLeft: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	exHeadImg1: {
		width: 16 * scale,
		height: 16 * scale,
		marginRight: 5 * scale
	},
	exHeadTitle: {
		fontSize: 14 * scale,
		color: '#222',
		marginRight: 5 * scale
	},
	longTime: {
		color: style.color.white,
		backgroundColor: '#49CAFF',
		fontSize: 11 * scale,
		height: 16 * scale,
		lineHeight: 16 * scale,
		borderRadius: 4 * scale,
		marginRight: 5 * scale,
		paddingLeft: 5 * scale,
		paddingRight: 5 * scale
	},
	exHeadImg2: {
		height: 12 * scale,
		width: 18 * scale,
	},
	exHeadHref: {
		fontSize: 13 * scale,
		color: style.color.extheme
	},
	exContent: {
		flexDirection: 'row',
		flexWrap: 'wrap',
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		paddingTop: 10 * scale
	},
	exComItem: {
		width: '50%',
		flexDirection: 'row',
		alignItems: 'center',
	},
	exComItemTe: {
		width: '100%'
	},
	exName: {
		fontSize: 12 * scale,
		color: style.color.inputPlaceholderColor,
		lineHeight: 26 * scale
	},
	exValue: {
		color: style.color.normal,
		marginHorizontal: 5, flexShrink: 1
	},
	listBox: {
		paddingBottom: 100 * scale,
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	},
	imgPosition: { position: 'absolute', bottom: 0, right: 12 * scale }

})